package com.mm.update.config;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ClassName: MyWebSocketHandler
 * Description:
 * date: 2025/4/18 16:37
 *
 * @author  
 * @since JDK 1.8
 */
//@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        // 处理接收消息
        String payload = message.getPayload();
        String userId = session.getHandshakeHeaders().getFirst("userId");
        sessions.forEach((id, s) -> {
            try {
                s.sendMessage(new TextMessage(userId+": " + payload));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws IOException {
        String userId = session.getHandshakeHeaders().getFirst("userId");
        sessions.put(userId, session);
        session.sendMessage(new TextMessage("连接成功！"));
    }
}